package com.book.bookmanager.controller;

import cn.hutool.json.JSONObject;
import cn.hutool.system.UserInfo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.book.bookmanager.pojo.Book;
import com.book.bookmanager.pojo.Head;
import com.book.bookmanager.pojo.Person;
import com.book.bookmanager.pojo.User;
import com.book.bookmanager.service.bookService;
import com.book.bookmanager.service.personService;
import com.book.common.vo.Result;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("book")
public class bookController {
    @Autowired
    private bookService bs;
    @Autowired
    private personService ps;

    /**
     * 全查
     */
//	@GetMapping("queryAll")
//	public Result<List<Book>> queryAll() {
//		List<Book> list = bs.queryAll();
//		/**
//		 * 存入model
//		 */
//		model.addAttribute("list", list);
//		return "showAll";
//		return Result.success(list,"查询成功");
//	}
//
    @GetMapping("book_list")
    @ApiOperation("获取图书列表")
    public Result<Map<String, Object>> getBookList(@RequestParam("token") String token) {
        Map<String, Object> data = bs.queryAll(token);
        if (data != null) {
            return Result.success(data, "获取图书列表成功");
        }
        return Result.fail(20003, "获取列表失败，请刷新");
    }

    @GetMapping("selectPage")
    public IPage<Book> selectPage() {
        /**
         * Page(current,size)
         * current:当前页,long类型
         * size:每页显示的数量,long类型
         * 可参考其构造方法
         */
        IPage<Book> userIPage = bs.selectPage(new Page<>(1, 5));
        return userIPage;
    }

    @RequestMapping("removeById")
    public String removeById(Integer id) {
        try {
            bs.removeById(id);
            return "redirect:/book/queryAll";
        } catch (Exception e) {
            return "error";
        }
    }

    @GetMapping("toAdd")
    public String toAdd() {

        return "addBook";
    }

    @RequestMapping("addBook")
    public String addBook(Book book) {
        try {
            bs.addBook(book);
            return "redirect:/book/queryAll";
        } catch (Exception e) {
            e.printStackTrace();
            return "error";
        }
    }


    @RequestMapping("upload")
    public String addBook(Book book,
                          /**
                           *定义一个 MultipartFile 类型的参数 file
                           * */
                          @RequestParam("file") MultipartFile file,
                          Model model) {
        //非空校验
        if ((file.getOriginalFilename().isEmpty())) {
            model.addAttribute("error", "error");
            return "redirect:/book/queryAll";
        }
        /***
         * 要上传的文件名
         */

        String originalFileName = file.getOriginalFilename();
        /***
         * 获取文件后缀
         */
        String suffix = originalFileName.substring(originalFileName.lastIndexOf("."));
        String fileTime = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        /**
         *生成图片名称，使用 UUID 避免相同图片名冲突，加上图片后缀
         */
        String photoName = fileTime + suffix;

        /**
         * 图片保存路径(绝对路径/相对路径)
         *这里为什么还要用相对路径，只用绝对路径不行么?
         * 因为禁止浏览器访问本地磁盘绝对路径路径，因此最简单的办法就是配置一个绝对路径用来保存文件，一个相对路径提供给浏览器访问
         **/
        String photoPathAbsolute = "C:/Users/lsx/IdeaProjects/bookmanager/src/main/webapp/uploaded" + photoName; //绝对路径
        String photoPathRelative = "uploaded/" + photoName; //相对路径
        //生成文件(绝对路径)
        File saveFile = new File(photoPathAbsolute);
        if (saveFile.exists()) {
            System.out.println("已存在");
        }
        try {
            file.transferTo(saveFile);
            book.setSfile(photoPathRelative);
            bs.addPhoto(book);
            bs.addBook(book);
            return "redirect:/book/queryAll";
        } catch (Exception e) {
            e.printStackTrace();
            return "error";
        }
    }


    @GetMapping("queryById")
    public String queryById(Integer id, Model model) {
        Book book = bs.queryById(id);
        model.addAttribute("book", book);
        return "update";
    }

    @RequestMapping("changeBook")
    public String changeBook(Book book) {
        try {
            bs.changeBook(book);
            return "redirect:/book/queryAll";
        } catch (Exception e) {
            return "error";
        }
    }

    @RequestMapping("buySuccess")
    public String buySuccess(HttpSession session, Model model, Integer id, Map<String, Object> map, HttpServletResponse response) {
        /**
         * 接收用户余额信息
         */
        try {
            String user1 = (String) session.getAttribute("user");
            System.out.println(user1);
            Person person = ps.queryByName(user1);
            Double balance = person.getBalance();
            /**
             * 接收图书信息
             */
            Book book = bs.queryById(id);
            Double price = book.getPrice();
            Double balance1 = balance - price;
            if (balance1 < 0.00) {
                model.addAttribute("余额不足，请充值");
                response.getWriter().write("<script>alert('余额不足，购买失败!');</script>");
                return "redirect:/book/toRecharge";
            } else {
                person.setBalance(balance1);
                ps.changePerson(person);
                model.addAttribute("购买成功");
                return "redirect:/book/queryAll";
            }
        } catch (Exception e) {
            return "error";
        }
    }

    @RequestMapping("toRecharge")
    public String toRecharge() {
        return "Recharge";
    }


}
